<template>
    <div>
      <dialog-edit :visible.sync="dialogVisible" :title="'硬件信息管理'" :editModel="editModel" :api="api" :form="form"
        :formRules="formRules" @onSaved="saveTab" @onSave="onSave" :autoSave="false">
        <el-tabs v-model="activeName"  @tab-click="tabClick">
          <el-tab-pane label="基础信息" name="info">
            <dym-form :editModel="editModel" :componentList="componentList" :formValue.sync="form"></dym-form>
           </el-tab-pane>
          <el-tab-pane v-if="showUpload" label="设备图片" name="deviceImg">
            <imgUpload v-model="form.fileId" :showFiles="true" @uploadSuccess="uploadSuccess" @fileRemove="fileRemove"/>
          </el-tab-pane>
          <el-tab-pane label="状态记录" name="stateLog">
             <el-table
              :data="tableData"
              style="width: 100%">
              <el-table-column
                prop="statusDay"
                label="状态日期"
                >
              </el-table-column>
              <el-table-column
                prop="useStatusLabel"
                label="状态">
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="变更记录" name="chengLog">
            <el-table
                :data="chengLogData"
                style="width: 100%">
                <el-table-column
                    prop="createTime"
                    label="变更时间"
                    width="180">
                      <template slot-scope="scope"  >
                    <span v-if="scope.row.checkStatus == '1'" style="color:red">{{scope.row.createTime}}</span>
                     <span v-if="scope.row.checkStatus == '3'" style="color:Darkorange">{{scope.row.createTime}}</span>
                    <span v-if="scope.row.checkStatus == '2'" style="color:green">{{scope.row.createTime}}</span>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="checkStatus"
                  label="状态"
                  width="180">
                  <template slot-scope="scope"  >
                    <span v-if="scope.row.checkStatus == '1'" style="color:red">审核中</span>
                    <span v-if="scope.row.checkStatus == '3'" style="color:Darkorange">退回</span>
                    <span v-if="scope.row.checkStatus == '2'" style="color:green">通过</span>
                  </template>
              </el-table-column>
                <el-table-column
                    prop="changeInfo"
                    label="变更信息">
                    <template slot-scope="scope"  >
                      <span v-if="scope.row.checkStatus == '1'" v-html="scope.row.changeInfo" style="color:red">{{scope.row.changeInfo}}</span>
                      <span v-if="scope.row.checkStatus == '3'" v-html="scope.row.changeInfo" style="color:Darkorange">{{scope.row.changeInfo}}</span>
                      <span v-if="scope.row.checkStatus == '2'" v-html="scope.row.changeInfo" style="color:green">{{scope.row.changeInfo}}</span>
                  </template>
                </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </dialog-edit>
    </div>
</template>

<script>
  import BaseDialog from '@/pages/BaseDialog'
  import DialogEdit from '@/components/dialog/DialogEdit'
  import dymForm from '@/components/element/dymForm'
  import { dvHardwareStatus, dvhardware, dvhardwareChange } from '@/api/business/businessApi'
  import componentApi from '@/api/component/componentApi'
  import { timestampToTime } from '@/filters/index'
  import {regExp} from '@/utils/reg'
  import imgUpload from '@/components/button/imgUpload.vue'
  export default {
    extends: new BaseDialog(),
    components: {
      DialogEdit,
      dymForm,
      imgUpload
    },
    data () {
      var validateCount = (rule, value, callback) => {
        if (!value) {
          callback(new Error('必填'))
        } else if (!regExp.number.test(value) || value < 0) {
          callback(new Error('请输入整数'))
        } else {
          callback()
        }
      }
      // 购买日期验证
      var checkbuyDate = (rule, value, callback) => {
        if (this.form.installDate) {
          this.$children[0].$refs.editForm.validateField('installDate')
        }
        if (this.form.startUseTime) {
          this.$children[0].$refs.editForm.validateField('startUseTime')
        }
        callback()
      }
      // 安装日期验证
      var checkinstallDate = (rule, value, callback) => {
        if (!value) return callback()
        if (this.form.startUseTime) {
          this.$children[0].$refs.editForm.validateField('startUseTime')
        }
        if (this.form.buyDate > value) {
          callback(new Error('安装日期不能小于购买日期'))
        }
        callback()
      }
      // 开始使用时间验证
      var checkstartUseTime = (rule, value, callback) => {
        if (!value) return callback()
        if (this.form.buyDate > value) {
          callback(new Error('开始使用时间不能小于购买日期'))
        } else if (this.form.installDate > value) {
          callback(new Error('开始使用时间不能小于安装日期'))
        } else {
          callback()
        }
      }
      return {
        saveFlag: false,
        showUpload: false,
        tableData: [],
        chengLogData: [],
        activeName: 'info',
        // 需要显示的每一项定义在这里
        componentList: [
          {
            label: '编码',
            prop: 'deviceCode', // 表单验证传入的值
            labelWidth: '120px',
            componentName: 'el-input',
            cols: [12, 12, 12, 12],
            placeholder: '请输入',
            value: 'deviceCode' // 字段显示的值
          },
          {
            label: '分类',
            prop: 'deviceType',
            labelWidth: '120px',
            componentName: 'dict',
            dictTypeCode: 'device_type',
            cols: [12, 12, 12, 12],
            placeholder: '请输入',
            value: 'deviceType'
          },
          {
            label: '设备名称',
            prop: 'hardwareName',
            labelWidth: '120px',
            componentName: 'el-input',
            cols: [24, 24, 24, 24],
            placeholder: '请输入',
            value: 'hardwareName'
          },
          {
            label: '所属部门',
            prop: 'oweOrgId',
            labelWidth: '120px',
            componentName: 'cascaderOrg',
            options: [],
            cascaderProps: {emitPath: false},
            cols: [12, 12, 12, 12],
            placeholder: '请先选择归属公司',
            value: 'oweOrgId'
          },
          {
            label: '购买日期',
            prop: 'buyDate',
            labelWidth: '120px',
            componentName: 'el-date-picker',
            cols: [12, 12, 12, 12],
            value: 'buyDate',
            placeholder: '请输入'
          },
          {
            label: '数量',
            prop: 'count',
            labelWidth: '120px',
            componentName: 'el-input',
            cols: [9, 9, 9, 9],
            value: 'count',
            placeholder: '请输入'
          },
          {
            label: '',
            prop: 'countUnit',
            labelWidth: '0px',
            componentName: 'dict',
            dictTypeCode: 'countUnit',
            cols: [3, 3, 3, 3],
            value: 'countUnit'
          },
          {
            label: '安装日期',
            prop: 'installDate',
            labelWidth: '120px',
            componentName: 'el-date-picker',
            cols: [12, 12, 12, 12],
            value: 'installDate',
            placeholder: '请输入'
          },
          {
            label: '规格型号',
            prop: 'specification',
            labelWidth: '120px',
            componentName: 'el-input',
            cols: [24, 24, 24, 24],
            value: 'specification',
            placeholder: '请输入'
          },
          {
            label: '使用单位',
            labelWidth: '120px',
            prop: 'useOrgId',
            componentName: 'cascaderOrg',
            options: [],
            cascaderProps: {emitPath: false},
            cols: [12, 12, 12, 12],
            placeholder: '请先选择归属公司',
            value: 'useOrgId'
          },
          {
            label: '使用人',
            prop: 'endUser',
            labelWidth: '120px',
            componentName: 'el-input',
            cols: [12, 12, 12, 12],
            value: 'endUser',
            placeholder: '请输入'
          },
          {
            label: '使用状态',
            prop: 'useStatus',
            labelWidth: '120px',
            componentName: 'dict',
            dictTypeCode: 'device_use_state',
            cols: [12, 12, 12, 12],
            value: 'useStatus',
            placeholder: '请输入'
          },
          {
            label: '开始使用时间',
            prop: 'startUseTime',
            labelWidth: '120px',
            componentName: 'el-date-picker',
            cols: [12, 12, 12, 12],
            value: 'startUseTime',
            placeholder: '请输入'
          },
          {
            label: '使用地址',
            prop: 'useAddr',
            labelWidth: '120px',
            componentName: 'el-input',
            cols: [24, 24, 24, 24],
            value: 'useAddr',
            placeholder: '请输入'
          },
          {
            label: '备注',
            prop: 'remarks',
            labelWidth: '120px',
            componentName: 'el-input',
            type: 'textarea',
            value: 'remarks',
            cols: [24, 24, 24, 24],
            placeholder: '请输入'
          }
        ],
        // 表单验证
        formRules: {
          // 表单字段名：[规则]
          deviceCode: [{ required: true, message: '必填', trigger: 'blur' }, {
            min: 1,
            max: 64,
            message: '长度在 1 到 64 个字符'
          }],
          deviceType: [{ required: true, message: '必填', trigger: 'blur' }],
          hardwareName: [{ required: true, message: '必填', trigger: 'blur' }, {
            min: 1,
            max: 150,
            message: '长度在 1 到 150 个字符'
          }],
          companyId: [{ required: true, message: '必填', trigger: 'blur, change' }],
          oweOrgId: [{ required: true, message: '必填', trigger: 'blur, change' }],
          count: [{ required: true, validator: validateCount, trigger: 'blur' }],
          useOrgId: [{ required: true, message: '必填', trigger: 'blur' }],
          countUnit: [{ required: true, message: '必填', trigger: 'blur' }],
          useStatus: [{ required: true, message: '必填', trigger: 'blur, change' }],
          specification: [{
            min: 1,
            max: 200,
            message: '长度在 1 到 200 个字符'
          }],
          endUser: [{
            min: 1,
            max: 50,
            message: '长度在 1 到 50 个字符'
          }],
          useAddr: [{
            min: 1,
            max: 300,
            message: '长度在 1 到 300 个字符'
          }],
          remarks: [{min: 1, max: 300, message: '长度在 1 到 300 个字符'}],
          buyDate: [{validator: checkbuyDate, trigger: 'change'}],
          installDate: [{validator: checkinstallDate, trigger: 'change'}],
          startUseTime: [{validator: checkstartUseTime, trigger: 'change'}]
        }
        // 编辑模式
        // editImg: ''
      }
    },
    watch: {
      'form.companyId' (val) {
        this.getOrgTree(val)
      }
      // 'activeName': {
      //   immediate: true,
      //   handler: function (val) {
      //     this.editImg = this.editModel
      //     console.log('val', val, this.editImg)
      //     if (this.editModel === 'V') {
      //       console.log(11111)
      //       if (val === 'deviceImg') {
      //         if (this.showUpload === true) {
      //           this.editImg = 'E'
      //         } else {
      //           this.editImg = 'V'
      //         }
      //         console.log('this.editModel', this.editModel)
      //       } else {
      //         this.editImg = 'V'
      //       }
      //     }
      //     // this.editImg === 'V'
      //   }
      // }
    },
    created () {
      this.init()
      this.showImgList()
    },
    methods: {
      getChangeInfo (id) {
        let checkStatus = '2'
        dvhardwareChange.getChangeInfo(id, checkStatus).then(res => {
            const data = res.data
            res.code === 0 && (this.chengLogData = data)
        })
      },
      getOrgTree (val) {
        componentApi.orgTree.get(val).then(res => {
          this.componentList.map(_ => {
            if (_.value === 'officeId') {
              _.options = res.data
            }
          })
        })
      },
      getStatus () {
        dvHardwareStatus.getStatus(this.form.id).then(res => {
          const data = res.data
          for (var i = 0; i < data.length; i++) {
            data[i].statusDay = timestampToTime(data[i].statusDay)
          }
          res.code === 0 && (this.tableData = data)
        })
      },
      tabClick (tab, event) {
        tab.name === 'stateLog' && this.getStatus()
      },
      init () {
        if (this.form.isImage) { // 有isImage 打开图片上传tab
          this.activeName = 'deviceImg'
        } else {
          this.activeName = 'info'
        }
        this.$set(this.form, 'oweOrgId', this.$store.state.user.officeId)
        this.$set(this.form, 'useOrgId', this.$store.state.user.officeId)
        if (this.form.id) {
          this.getChangeInfo(this.form.id)
          this.showUpload = true
        }
      },
      saveTab () {
        if (!this.saveFlag) {
          if (this.form.id) {
            if (this.editModel !== 'V') {
              this.saveForm()
            }
          } else {
            if (!this.showUpload) {
              this.newAdd()
            } else {
              this.$emit('handSearch')
              this.dialogVisible = false
            }
          }
        } else {
          this.dialogVisible = false
          this.$emit('handSearch')
        }
      },
      // 保存表单数据
      saveForm () {
        dvhardware.update(this.form.id, this.form).then(res => {
          if (res.code === 0) {
            this.dialogVisible = false
            this.$emit('handSearch')
            this.success('修改成功')
          } else if (res.code === -1) {
            this.error(res.msg)
          }
        })
      },
      // 保存图片数据
      saveImag () {
        let obj = {
          bizId: this.form.id,
          attachmentId: this.form.fileId
        }
        dvhardware.fileUpload(obj).then(res => {
          this.$emit('handSearch')
        })
      },
      // 新增数据
      newAdd () {
        dvhardware.create(this.form).then(res => {
          if (res.code === 0) {
            this.showUpload = true
            this.activeName = 'deviceImg'
            // this.saveFlag = true
            this.$emit('handSearch')
            this.success('新增成功')
          } else if (res.code === -1) {
            this.error(res.msg)
          }
        })
      },
      // 上传文件成功后回调
      uploadSuccess (returnData, rowIndex, rowData, fileList) {
        this.success('上传成功')
        this.$nextTick(() => {
          this.saveImag()
        })
      },
      // 文件删除
      fileRemove (val, fileList) {
        this.$nextTick(() => {
          this.saveImag()
        })
      },
      showImgList () {
        dvhardware.showImgList(this.form.id).then(res => {
          res.code === 0 && (this.form.fileId = res.data.fileId.join(','))
        })
      }
    }
  }
</script>
